<?php

namespace app\api\controller\minishop;

use app\common\controller\Api;
use Think\Db;

/**
 * 首页接口
 */
class Order extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    

    /**
     * 创建订单接口
     * @ApiMethod (POST)
     */
    public function add()
    {
        $data = $this->request->post();

        // 检查必填字段
        if (empty($data['user_id']) || empty($data['order_images']) || empty($data['estimated_weight']) ||
            empty($data['recycling_category']) || empty($data['collection_address']) || empty($data['collection_time'])) {
            $this->error('缺少必填字段');
        }

        // 准备插入数据
        $orderData = [
            'user_id' => $data['user_id'],
            'order_images' => json_encode($data['order_images']),
            'estimated_weight' => $data['estimated_weight'],
            'recycling_category' => $data['recycling_category'],
            'collection_address' => $data['collection_address'],
            'additional_instructions' => $data['additional_instructions'] ?? '',
            'collection_time' => strtotime($data['collection_time']),
            'createtime' => time(),
            'updatetime' => time(),
            'order_status' => '已下单'
        ];

        // 插入订单数据
        $orderId = Db::name('minishop_orders')->insertGetId($orderData);
        if ($orderId) {
            $this->success('订单创建成功', ['order_id' => $orderId]);
        } else {
            $this->error('订单创建失败');
        }
    }

    /**
     * 获取订单列表接口
     * @ApiMethod (GET)
     */
    public function list()
    {
        $userId = $this->request->get('user_id');
        // if (empty($userId)) {
        //     $this->error('用户ID不能为空');
        // }

        // 查询用户的订单列表
        $orders = Db::name('minishop_orders')
            // ->where('user_id', $userId)
            ->order('createtime desc')
            ->select();

        if ($orders) {
            $this->success('订单列表获取成功', $orders);
        } else {
            $this->error('暂无订单');
        }
    }
    

}